home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10069 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: EU.net!sun4nl!xs4all!falstaff
  2. From: falstaff@xs4all.nl (Falstaff)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Determining the length of an int in string form
  5. Date: 14 Mar 1996 17:13:01 GMT
  6. Organization: XS4ALL, networking for the masses
  7. Message-ID: <4i9k2t$m6p@news.xs4all.nl>
  8. References: <3146D058.DD7@cbm.com>
  9. NNTP-Posting-Host: xs1.xs4all.nl
  10. X-Newsreader: NN version 6.5.0 #666 (NOV)
  11.  
  12. Dave Payne <paynedc@cbm.com> writes:
  13.  
  14. >Consider this:
  15.  
  16. >I have a variable of type int, and I would like to use the sprintf() 
  17. >function to write this variable to a string.  However, I want to 
  18. >dynamically allocate the space for the string, and only malloc enough 
  19. >space to hold the int.  Here's a code fragment that may illustrate this 
  20. >more clearly:
  21.  
  22. >void func1()  {
  23.  
  24. >  int     i = 1234;
  25. >  char     *a;
  26.  
  27. >  a = malloc(strlen("The value of i is ") + 4 + 1);
  28. >  sprintf(a,"%s%d","The value of i is ",i);
  29.  
  30. Nasty programming here -- what if you change one string and not the
  31. other?
  32.  
  33. >In this example, I hardcoded the 4, because I knew that 1234 was 4 
  34. >characters long.  I would like to be able to determine this at runtime, 
  35. >and malloc enough space accordingly.
  36.  
  37. Why?
  38.  
  39. In one recent case I needed something like this too and used strdup()
  40. on the result of a sprintf().
  41.  
  42. Of course, your *original* question is answered by
  43.  
  44. int length_of_decimal(unsigned n)
  45. {  int i=1;
  46.  
  47.    do
  48.    {  n/=10;
  49.       i++;
  50.    } while(n);
  51.  
  52.    return i;
  53. }
  54.  
  55. Frank
  56. --
  57. The famous GIICM now on line:  http://www.xs4all.nl/~falstaff/GIICM.html
  58. ------------------------------------------------------------------------
  59. Frank A. Vorstenbosch        +31-(70)-355 5241        falstaff@xs4all.nl
  60.